
import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Brain, CheckCircle, X, Lightbulb, Zap } from 'lucide-react';
import { InvokeLLM } from "@/api/integrations";

export default function SmartRecommendation({ 
  crossingPoint, 
  project, 
  methodTemplates = [], 
  onApply, 
  onDismiss 
}) {
  const [recommendation, setRecommendation] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    generateRecommendation();
  }, [crossingPoint, project, methodTemplates]);

  const generateRecommendation = async () => {
    if (!crossingPoint || methodTemplates.length === 0) {
      console.log("跨越点或模板数据不完整，跳过推荐");
      setIsLoading(false);
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      const availableMethods = methodTemplates.map(template => ({
        code: template.methodCode,
        name: template.methodName,
        description: template.description,
        scenarios: template.applicableScenarios || []
      }));

      console.log("可用施工方法:", availableMethods);

      const prompt = `作为电力工程施工专家，请根据以下跨越点信息推荐最适合的施工方法：

跨越点信息：
- 跨越类型：${crossingPoint.crossingType}
- 跨越对象：${crossingPoint.crossingObject}
- 档距长度：${crossingPoint.spanLength || '未知'}米
- 跨越高度：${crossingPoint.crossingHeight || '未知'}米
- 难度等级：${crossingPoint.difficultyLevel}
- 优先级：${crossingPoint.priority}
- 设计风速：${crossingPoint.windSpeed || '未知'}m/s
- 覆冰厚度：${crossingPoint.iceThickness || '未知'}mm

项目信息：
- 电压等级：${project?.voltageLevel || '未知'}
- 项目名称：${project?.name || '未知'}

可选施工方法：
${availableMethods.map(method => 
  `- ${method.code}: ${method.name}\n  描述：${method.description}\n  适用场景：${method.scenarios.join('、')}`
).join('\n')}

请分析并推荐最适合的施工方法，要求返回JSON格式：
{
  "recommended_method": "推荐的方法代码",
  "confidence": 95,
  "reasoning": "选择理由的详细说明",
  "advantages": ["优势1", "优势2", "优势3"],
  "considerations": ["注意事项1", "注意事项2"],
  "alternative_methods": [
    {
      "method": "备选方法代码",
      "reason": "备选理由"
    }
  ]
}`;

      console.log("发送推荐请求...");
      const response = await InvokeLLM({
        prompt: prompt,
        addContextFromInternet: false,
        responseJsonSchema: {
          type: "object",
          properties: {
            recommended_method: { type: "string" },
            confidence: { type: "number" },
            reasoning: { type: "string" },
            advantages: { type: "array", items: { type: "string" } },
            considerations: { type: "array", items: { type: "string" } },
            alternative_methods: {
              type: "array",
              items: {
                type: "object",
                properties: {
                  method: { type: "string" },
                  reason: { type: "string" }
                }
              }
            }
          }
        }
      });

      console.log("推荐结果:", response);
      setRecommendation(response);
    } catch (error) {
      console.error('生成推荐失败:', error);
      setError('智能推荐功能暂时不可用，请手动选择施工方法。');
    } finally {
      setIsLoading(false);
    }
  };

  const handleApply = () => {
    if (recommendation && onApply) {
      console.log("应用推荐方法:", recommendation.recommended_method);
      onApply(recommendation.recommended_method);
    }
  };

  if (isLoading) {
    return (
      <Card className="mb-6 border-blue-200 bg-blue-50">
        <CardContent className="pt-6">
          <div className="flex items-center gap-3">
            <div className="animate-spin">
              <Brain className="w-6 h-6 text-blue-600" />
            </div>
            <div>
              <h3 className="font-semibold text-blue-900">智能分析中...</h3>
              <p className="text-blue-700 text-sm">正在分析跨越点特征，推荐最适合的施工方法</p>
            </div>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card className="mb-6 border-yellow-200 bg-yellow-50">
        <CardContent className="pt-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Lightbulb className="w-6 h-6 text-yellow-600" />
              <div>
                <h3 className="font-semibold text-yellow-900">智能推荐暂不可用</h3>
                <p className="text-yellow-700 text-sm">{error}</p>
              </div>
            </div>
            <Button variant="ghost" size="icon" onClick={onDismiss}>
              <X className="w-4 h-4" />
            </Button>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (!recommendation) {
    return null;
  }

  const recommendedTemplate = methodTemplates.find(t => t.methodCode === recommendation.recommended_method);

  return (
    <Card className="mb-6 border-green-200 bg-gradient-to-r from-green-50 to-blue-50">
      <CardHeader className="pb-4">
        <div className="flex items-center justify-between">
          <CardTitle className="flex items-center gap-2 text-green-900">
            <Brain className="w-5 h-5" />
            智能施工方案推荐
            <Badge className="bg-green-100 text-green-700 border-green-200">
              <Zap className="w-3 h-3 mr-1" />
              置信度 {recommendation.confidence}%
            </Badge>
          </CardTitle>
          <Button variant="ghost" size="icon" onClick={onDismiss}>
            <X className="w-4 h-4" />
          </Button>
        </div>
      </CardHeader>
      
      <CardContent className="space-y-4">
        {/* 推荐方法 */}
        <div className="bg-white rounded-lg p-4 border border-green-200">
          <div className="flex items-center gap-3 mb-3">
            <CheckCircle className="w-5 h-5 text-green-600" />
            <div>
              <h4 className="font-semibold text-gray-900">
                推荐方法：{recommendedTemplate?.methodName || recommendation.recommended_method}
              </h4>
              <p className="text-sm text-gray-600">
                {recommendedTemplate?.description}
              </p>
            </div>
          </div>
          
          <div className="text-sm text-gray-700 mb-3">
            <strong>推荐理由：</strong>{recommendation.reasoning}
          </div>
          
          {recommendation.advantages && recommendation.advantages.length > 0 && (
            <div className="mb-3">
              <h5 className="font-medium text-gray-800 mb-2">主要优势：</h5>
              <ul className="list-disc list-inside space-y-1 text-sm text-gray-700">
                {recommendation.advantages.map((advantage, index) => (
                  <li key={index}>{advantage}</li>
                ))}
              </ul>
            </div>
          )}
          
          {recommendation.considerations && recommendation.considerations.length > 0 && (
            <div className="mb-3">
              <h5 className="font-medium text-gray-800 mb-2">注意事项：</h5>
              <ul className="list-disc list-inside space-y-1 text-sm text-orange-700">
                {recommendation.considerations.map((consideration, index) => (
                  <li key={index}>{consideration}</li>
                ))}
              </ul>
            </div>
          )}
        </div>

        {/* 备选方案 */}
        {recommendation.alternative_methods && recommendation.alternative_methods.length > 0 && (
          <div>
            <h5 className="font-medium text-gray-800 mb-2">备选方案：</h5>
            <div className="space-y-2">
              {recommendation.alternative_methods.map((alt, index) => {
                const altTemplate = methodTemplates.find(t => t.methodCode === alt.method);
                return (
                  <div key={index} className="bg-gray-50 rounded p-3 text-sm">
                    <span className="font-medium">{altTemplate?.methodName || alt.method}</span>
                    <span className="text-gray-600 ml-2">- {alt.reason}</span>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* 操作按钮 */}
        <div className="flex gap-3 pt-2">
          <Button 
            onClick={handleApply}
            className="bg-green-600 hover:bg-green-700"
          >
            <CheckCircle className="w-4 h-4 mr-2" />
            采用推荐方案
          </Button>
          <Button variant="outline" onClick={onDismiss}>
            手动选择
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
